<template>
    <div class="bg-surface-0 dark:bg-surface-900 text-3xl ">

        <div v-for="(Achievment, i) in AchievmentList" :key="i" class="col-span-12 lg:m-24 lg:p-4 sm:p-0 sm:m-0">
            <div class="bg-white dark:bg-gray-800 rounded-lg shadow-md p-4 h-full">
                <div class="flex items-center gap-4">
                    <!-- 左侧图片容器 -->
                    <div class="flex-1 justify-center items-center">

                        <img :src="Achievment.Img" :alt="Achievment.Label"
                            class="w-full object-cover rounded-lg cursor-pointer" @click="openModal(Achievment.Img)" />

                    </div>

                    <!-- 右侧内容容器 -->
                    <div class="flex-1 p-10">
                        <h4 class=" text-red-600">
                            {{ Achievment.Label }}
                        </h4>
                        <p class="text-surface-600 dark:text-surface-200">
                            描述：{{ Achievment.Desc }}
                        </p>
                        <p class="text-surface-600 dark:text-surface-200">
                            等级:{{ Achievment.Level }}
                        </p>
                        <p class="text-surface-600 dark:text-surface-200">
                            类别：{{ Achievment.Kind }}
                        </p>
                        <p class="text-surface-600 dark:text-surface-200">
                            获证时间：{{ CommonService.formatDate(Achievment.GetDate) }}
                        </p>
                        <p class="text-surface-600 dark:text-surface-200">
                            上传时间：{{ CommonService.formatDate(Achievment.Creattime) }}
                        </p>
                    </div>
                    <button @click="deleteArchive(Achievment.Id)" v-if="Achievment.UserSN == currentUser.sn"
                        class=" relative top-2 right-2 z-10 bg-black rounded-full w-8 h-8 flex items-center justify-center shadow hover:bg-gray-100">
                        ×
                    </button>
                </div>
            </div>
        </div>
        <div class=" justify-center text-center">
            <hr> <br>
            ---------------在下面添加新证书---------------
        </div>

        <!-- 添加证书的表单 -->
        <div class="col-span-12 p-0 m-24 lg:p-4">
            <form @submit.prevent="addAchievement"
                class="bg-white dark:bg-gray-800 rounded-lg shadow-md p-6 space-y-4  ">
                <div>
                    <label for="label" class="block text-md font-medium text-gray-700 dark:text-gray-300">名称:</label>
                    <input type="text" id="label" v-model="newAchievment.Label" required placeholder="填写证书的名称"
                        class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-md" />
                </div>

                <div>
                    <label for="level" class="block text-md font-medium text-gray-700 dark:text-gray-300">等级:</label>
                    <input type="text" id="level" v-model="newAchievment.Level" required placeholder="国家级、省级、市级、校级"
                        class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-md" />
                </div>
                <div>
                    <label for="kind" class="block text-md font-medium text-gray-700 dark:text-gray-300">类别:</label>
                    <input type="text" id="kind" v-model="newAchievment.Kind" required
                        placeholder="行业资格、奖学金、软考、等级证书、竞赛类"
                        class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-md" />
                </div>
                <div>
                    <label for="getDate"
                        class="block text-md font-medium text-gray-700 dark:text-gray-300">获证时间:</label>
                    <input type="date" id="getDate" v-model="newAchievment.GetDate" required
                        class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-md" />
                </div>
                <div>
                    <label for="img" class="block text-md font-medium text-gray-700 dark:text-gray-300">图片:</label>
                    <InputText type="file" id="screenshot0" @change="onUploadImage($event, 'displayImage')"
                        accept="image/*" style="display: none" />
                    <img id="displayImage" ref="faceImageRef"
                        :src="newAchievment.Img ? newAchievment.Img : defaultImage" width="100%"
                        style="max-height: 100px; max-width: 100px; border-radius: 4px"
                        onclick=" document.getElementById('screenshot0').click();" />
                </div>
                <div>
                    <label for="desc" class="block text-md font-medium text-gray-700 dark:text-gray-300">其他描述:</label>
                    <textarea id="desc" v-model="newAchievment.Desc" required placeholder="填写证书的其他事情"
                        class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-md"></textarea>
                </div>
                <div class=" text-center">
                    <button type="submit"
                        class="mt-4 w-1/5  bg-indigo-600 text-white font-bold py-2 px-4 rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                        确认添加
                    </button>
                </div>
            </form>
        </div>
        <!-- 如何让模态框 的最大高宽不超过屏幕，特别是关闭按钮X 必须留在屏幕中-->
        <div v-if="showModal" class="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 p-4">
            <div
                class="bg-white rounded-lg shadow-lg relative flex flex-col max-h-[calc(100vh-2rem)] max-w-[calc(100vw-2rem)]">
                <button @click="closeModal"
                    class="absolute top-2 right-2 z-10 bg-white rounded-full w-8 h-8 flex items-center justify-center shadow hover:bg-gray-100">
                    ×
                </button>
                <img :src="selectedImage" alt="Selected Image" class="object-contain max-h-[calc(100vh-3rem)] p-2" />
            </div>
        </div>
    </div>
</template>
<script setup>
import defaultImageSrc from "@/assets/img.png"; // 导入默认图片
import { AchievmentService } from "@/service/AchievmentService";
import { onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { CommonService } from "../common";
const faceImageRef = ref(null);
const AchievmentList = ref([]);
const route = useRoute();
const router = useRouter();
const currentUser = ref({});
const showModal = ref(false);
const selectedImage = ref("");
const defaultImage = defaultImageSrc; // 使用导入的默认图片
const handleResult = (level, title) => {
    if (level != "success") {
        alert(title);
    }
    // toast.add({ severity: level, summary: "Error Message", detail: title, life: 3000 });
};
let snStr = "";
onMounted(() => {
    snStr = route.params.sn + "";
    let AuthorizationStr = localStorage.getItem("Authorization");
    const payload = CommonService.parseJwtPayload(AuthorizationStr);
    if (!payload) {
        router.push({ name: "login" });
        return;
    }
    try {
        if (payload.sn == snStr) {
            currentUser.value = payload;
        } else {
        }
    } catch (error) { }
    queryAchievments(snStr);
});

function onUploadImage(e, name) {
    const file = e.target.files[0];
    if (file) {
        if (file.size > 512 * 1024) {
            const reader = new FileReader();
            reader.onload = function (event) {
                const img = new Image();
                img.onload = function () {
                    const canvas = document.createElement("canvas");
                    const MAX_WIDTH = 1024; // 定义最大宽度
                    const MAX_HEIGHT = 768; // 定义最大高度
                    let width = img.width;
                    let height = img.height;
                    if (width > MAX_WIDTH) {
                        height = (height * MAX_WIDTH) / width;
                        width = MAX_WIDTH;
                    }
                    if (height > MAX_HEIGHT) {
                        width = (width * MAX_HEIGHT) / height;
                        height = MAX_HEIGHT;
                    }
                    canvas.width = width;
                    canvas.height = height;
                    const ctx = canvas.getContext("2d");
                    ctx.drawImage(img, 0, 0, width, height);
                    const compressedDataUrl = canvas.toDataURL(file.type, 0.7);
                    if (name === "displayImage") {
                        faceImageRef.value?.setAttribute("src", compressedDataUrl);
                        // 问：下面的formData.value.displayImageData  格式是base64编码吗
                        newAchievment.value.ImgData = compressedDataUrl;
                    }
                };
                img.setAttribute("src", event.target.result + "");
            };
            reader.readAsDataURL(file);
        } else {
            const reader = new FileReader();
            reader.onload = function (event) {
                if (name === "displayImage") {
                    faceImageRef.value?.setAttribute("src", event.target.result + "");
                    // 存储未压缩的图像数据
                    newAchievment.value.ImgData = event.target.result + "";
                }
            };
            reader.readAsDataURL(file);
        }
    }
}
const queryAchievments = async (snStr) => {
    try {
        const result = await AchievmentService.queryAchievments(snStr);
        if (result.Code === 1000) {

            AchievmentList.value = result.Data;
        } else {
            alert(result.Title);
        }
    } catch (error) {
        alert(error);
    }
};

const newAchievment = ref({
    Label: "",
    Desc: "",
    Level: "",
    Kind: "",
    GetDate: "",
    Creattime: "",
    Img: "",
    ImgData: "",
});

const handleFileUpload = (event) => {
    const file = event.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = (e) => {
            newAchievment.value.Img = e.target.result;
        };
        reader.readAsDataURL(file);
    }
};

const addAchievement = async () => {
    try {

        newAchievment.value.Creattime = new Date().toISOString();
        newAchievment.value.GetDate = new Date(newAchievment.value.GetDate).toISOString();
        const result = await AchievmentService.addAchievments(snStr, newAchievment.value);
        if (result.Code === 1000) {
            AchievmentList.value.push(result.Data);
            newAchievment.value = {
                Label: "",
                Desc: "",
                Level: "",
                Kind: "",
                GetDate: "",
                Creattime: "",
                Img: null,
                ImgData: "",
            };
            document.getElementById("displayImage").src = defaultImage;
            alert("添加成功");
        } else {
            alert(result.Title);
        }
    } catch (error) {
        alert(error);
    }
};

const openModal = (imgUrl) => {
    selectedImage.value = imgUrl;
    showModal.value = true;
};

const closeModal = () => {
    showModal.value = false;
};


const deleteArchive = async (id) => {
    if (!confirm('确定要删除此证书吗？')) {
        return  // 用户点击取消则直接返回
    }
    try {
        const result = await AchievmentService.deleteAchievments(id);
        if (result.Code === 1000) {
            AchievmentList.value = AchievmentList.value.filter(item => item.Id !== id);
        }
        alert(result.Title);
    } catch (error) {
        alert(error);
    }
};


</script>
